#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.hook;

import java.util.LinkedList;
import java.util.List;

import com.networknt.server.ShutdownHookProvider;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Shutdown implements ShutdownHookProvider {
	private static List<Object> shutdowns = new LinkedList<>();
	private static List<Object> runtimes = new LinkedList<>();

	public Shutdown() {
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				shutdown(runtimes);
			}
		});
	}

	@Override
	public void onShutdown() {
		shutdown(shutdowns);
	}

	private void shutdown(List<Object> shutdowns) {
		log.info("shutdown {}", shutdowns.size());
		for (Object shutdown : shutdowns) {
			try {
				if (shutdown instanceof Runnable) {
					((Runnable) shutdown).run();
				} else if (shutdown instanceof AutoCloseable) {
					((AutoCloseable) shutdown).close();
				} else if (shutdown instanceof Thread) {
					((Thread) shutdown).start();
				} else {
					log.warn("unsupported shutdown " + shutdown);
					continue;
				}
				log.info("shutdown " + shutdown);
			} catch (Exception e) {
				log.warn("{} shutdown failed: {}", shutdown, e.getMessage());
			}
		}
	}

	/**
	 * @param shutdown 支持Runnable、Thread、AutoClosable
	 */
	public static void add(Object shutdown) {
		shutdowns.add(shutdown);
	}

	public static void addRuntime(Object shutdown) {
		runtimes.add(shutdown);
	}
}
